package org.ghost.http.okhttp.log;

import okhttp3.*;
import okio.Buffer;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017-07-18.
 */
public class LoggerInterceptor implements Interceptor {
    private static Logger logger = Logger.getLogger("LoggerInterceptor");
    public static final String TAG = "OkHttpUtils";
    private boolean showResponse;

    public LoggerInterceptor(boolean showResponse) {
        this.showResponse = showResponse;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        logForRequest(request);
        Response response = chain.proceed(request);
        return logForResponse(response);
    }

    private Response logForResponse(Response response) {
        try {
            logger.info("========response'log=======");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            logger.info("url : " + clone.request().url());
            logger.info("code : " + clone.code());
            logger.info("protocol : " + clone.protocol());
            if (clone.message() != null && clone.message().length() > 0)
                logger.info("message : " + clone.message());

            if (showResponse) {
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        logger.info("responseBody's contentType : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            logger.info("responseBody's content : " + resp);

                            body = ResponseBody.create(mediaType, resp);
                            return response.newBuilder().body(body).build();
                        } else {
                            logger.info("responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                        }
                    }
                }
            }

            logger.info("========response'log=======end");
        } catch (Exception e) {
            logger.log(Level.SEVERE, "logForResponse出现错误:{}", e);
        }

        return response;
    }

    private void logForRequest(Request request) {
        try {
            String url = request.url().toString();
            Headers headers = request.headers();

            logger.info("========request'log=======");
            logger.info("method : " + request.method());
            logger.info("url : " + url);
            if (headers != null && headers.size() > 0) {
                logger.info("headers : " + headers.toString());
            }
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null) {
                    logger.info("requestBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        logger.info("requestBody's content : " + bodyToString(request));
                    } else {
                        logger.info("requestBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
            logger.info("========request'log=======end");
        } catch (Exception e) {
            logger.log(Level.SEVERE, "logForRequest出现错误:{}", e);
        }
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") || mediaType.subtype().equals("xml") || mediaType.subtype().equals("html") || mediaType.subtype().equals("webviewhtml")) {
                return true;
            }
        }
        return false;
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            logger.log(Level.SEVERE, "bodyToString出现错误:{}", e);
            return "something error when show requestBody.";
        }
    }
}
